<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes"/>
	<xsl:template match="/CogDataSet">
		<xsl:for-each select="TableInfo">
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[<xsl:value-of select="Schema"/>].[<xsl:value-of select="ManagedTable"/>_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [<xsl:value-of select="Schema"/>].[<xsl:value-of select="ManagedTable"/>_Update]
GO

CREATE PROCEDURE [<xsl:value-of select="Schema"/>].[<xsl:value-of select="ManagedTable"/>_Update]
(
	<xsl:for-each select="ColumnInfo[IsComputed='false']"><xsl:choose>
		<xsl:when test="IsPrimaryKey='true' and IsIdentity='false'">@<xsl:value-of select="Column"/><xsl:text> </xsl:text><xsl:value-of select="DataType"/>,
	@New<xsl:value-of select="Column"/><xsl:text> </xsl:text><xsl:value-of select="DataType"/><xsl:if test="not(position()=last())">,</xsl:if>
	</xsl:when>
		<xsl:otherwise>@<xsl:value-of select="Column"/><xsl:text> </xsl:text><xsl:if test="DataType='XML'">VARCHAR(MAX)</xsl:if><xsl:if test="DataType!='XML'"><xsl:value-of select="DataType"/></xsl:if><xsl:if test="not(position()=last())"><xsl:if test="IsNullable = 'true'"> = NULL</xsl:if>,
	</xsl:if></xsl:otherwise>
	</xsl:choose></xsl:for-each>
)
AS
BEGIN
UPDATE [<xsl:value-of select="Schema"/>].[<xsl:value-of select="Table"/>]
SET <xsl:for-each select="ColumnInfo[IsPrimaryKey='false' and IsIdentity='false' and IsComputed='false']">[<xsl:value-of select="Column"/>] = <xsl:choose>
	<xsl:when test="IsPrimaryKey='true'">@New<xsl:value-of select="Column"/></xsl:when>
	<xsl:otherwise><xsl:if test="DataType='XML'">CAST(@<xsl:value-of select="Column"/> AS XML)</xsl:if><xsl:if test="DataType!='XML'">@<xsl:value-of select="Column"/></xsl:if></xsl:otherwise>
</xsl:choose><xsl:if test="not(position()=last())">, 
	</xsl:if></xsl:for-each>
WHERE <xsl:for-each select="ColumnInfo[IsPrimaryKey='true']">[<xsl:value-of select="Column"/>] = @<xsl:value-of select="Column"/><xsl:if test="not(position()=last())"> AND
</xsl:if>
</xsl:for-each>
END
GO
		</xsl:for-each>
	</xsl:template>
</xsl:stylesheet>
